<?php

namespace Iaem\MobileBundle\Controller;

use Iaem\UserBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    public function connectAction()
    {
        $request = $this->getRequest();

        $response = ['status' => 'success'];

        $repo = $this->getDoctrine()->getRepository('HomeBundle:Vote');
        $response['data']['countAll'] = $repo->getCountAll();

        /** @var User $user */
        $user = $this->get('fos_user.user_manager')
            ->findUserBy([
                'email' => $request->request->get('email'),
                'device_id' => $request->request->get('device_id')
            ]);

        if (null === $user) {

            /** @var User $user */
            $user = $this->get('fos_user.user_manager')->createUser();

            $user->setUsername($request->request->get('email'));
            $user->setEmail($request->request->get('email'));
            $user->setDeviceId($request->request->get('device_id'));

            $password = $this->get('security.encoder_factory')
                ->getEncoder($user)
                ->encodePassword($request->request->get('password'), $user->getSalt());

            $token = md5($password.$request->request->get('device_id').time());

            $user->setDeviceAccessToken($token);

            $user->setPassword($password);
            $user->setEnabled(true);
            $this->get('fos_user.user_manager')->updateUser($user);

            $response['data']['userId'] = $user->getId();
            $response['data']['token'] = $user->getDeviceAccessToken();
        } else {
            $password = $this->get('security.encoder_factory')
                ->getEncoder($user)
                ->encodePassword($request->request->get('password'), $user->getSalt());

            if ($user->getPassword() != $password) {

                $response['status'] = 'fail';
                $response['data'] = [
                    'password' => "password not match!",
                ];
            } else {
                $response['data'] = [
                    'userId' => $user->getId(),
                    'token' => $user->getDeviceAccessToken()
                ];
            }
        }

        return new Response(json_encode($response));
    }

    public function voteAction()
    {
        $request = $this->getRequest();

        $request->request->get('deviceId');
        $request->request->get('token');

        $resp = ['status' => 'success'];

        if ($request->request->get('deviceId') && $request->request->get('token')) {
             $user = $this->get('fos_user.user_manager')
                ->findUserBy([
                    'device_id' => $request->request->get('deviceId'),
                    'device_access_token' => $request->request->get('token')
                ]);
            if ($user) {
                if ($this->get('voter')->vote($user)) {
                    $repo = $this->getDoctrine()->getRepository('HomeBundle:Vote');
                    $response['data']['countAll'] = $repo->getCountAll();
                } else {
                    $resp['status'] = 'fail';
                    $resp['data'] = ['Ошибка при выполнении. Возможно с последнего момента нажатия кнопки не прошло 24 часа.'];
                }
            } else {
                $resp['status'] = 'fail';
                $resp['data' ] = ['Не верные данные для авторизации. Пользоветель не найден.'];
            }
        } else {
            $resp['status'] = 'fail';
            $resp['data' ] = ['Не хватает данных для авторизации.'];
        }

        return new Response(json_encode($resp));
    }

    public function finishAction()
    {
        $request = $this->getRequest();

        $request->request->get('deviceId');
        $request->request->get('token');

        $resp = ['status' => 'success'];

        if ($request->request->get('deviceId') && $request->request->get('token')) {
            $user = $this->get('fos_user.user_manager')
                ->findUserBy([
                    'device_id' => $request->request->get('deviceId'),
                    'device_access_token' => $request->request->get('token')
                ]);

            if ($user) {
                $repo = $this->getDoctrine()->getRepository('HomeBundle:Vote');
                $resp['data'] = ['countToday' => $repo->getTodayCount()];
                $response['data']['countAll'] = $repo->getCountAll();
            } else {
                $resp['status'] = 'fail';
                $resp['data' ] = ['Не верные данные для авторизации. Пользоветель не найден.'];
            }

        } else {
            $resp['status'] = 'fail';
            $resp['data' ] = ['Не хватает данных для авторизации.'];
        }

        return new Response(json_encode($resp));
    }

}
